﻿using Permission.Abstract;
using System;
using System.Collections.Generic;
//using JetBrains.Annotations;

namespace Permission;

public class PermissionDefinitionContext : IPermissionDefinitionContext
{
    public IServiceProvider ServiceProvider { get; }

    public Dictionary<string, PermissionGroupDefinition> Groups { get; }

    public PermissionDefinitionContext(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
        Groups = new Dictionary<string, PermissionGroupDefinition>();
    }

    public virtual PermissionGroupDefinition AddGroup(string name, string displayName = "")
    {

        if (Groups.ContainsKey(name))
        {
            throw new Exception($"已经存在权限则: {name}");
        }

        return Groups[name] = new PermissionGroupDefinition(name, displayName);
    }


    public virtual PermissionGroupDefinition GetGroup(string name)
    {
        if (!string.IsNullOrWhiteSpace(name) && !Groups.ContainsKey(name))
        {
            throw new Exception($"不存在权限组: {name}");
        }

        if (Groups?.Values.Count > 0 && string.IsNullOrWhiteSpace(name))
        {
            return Groups?.Values.FirstOrDefault() ?? null;
        }
        throw new Exception($"错误权限组: {name}");
    }


    public virtual void RemoveGroup(string name)
    {

        if (!Groups.ContainsKey(name))
        {
            throw new Exception($"不存在权限组: {name}");
        }

        Groups.Remove(name);
    }

    public virtual PermissionDefinition GetPermissionOrNull(string name)
    {

        foreach (var groupDefinition in Groups.Values)
        {
            var permissionDefinition = groupDefinition.GetPermissionOrNull(name);

            if (permissionDefinition != null)
            {
                return permissionDefinition;
            }
        }
        return null;
    }
}
